#!/usr/bin/env python
# encoding: utf-8
"""
netpop_manager.py

Created by Troy Ruths on 2011-02-28.
Copyright (c) 2011 __MyCompanyName__. All rights reserved.
"""

import sys
import getopt
from bourbon.util import load_defaults

help_message = '''
	The help message goes here.
	'''

def run_manager(args):
	try:
		opts, args = getopt.getopt(args, "", ["help", "db=","port=","host="])
	except getopt.error, msg:
		raise Usage(msg)

	# option processing
	data = load_defaults()
	db,port,host = None,8000,'localhost'
	if 'db_address' in data: db = data['db_address']
	if 'port' in data: port = int(data['port'])
	if 'host' in data: host = data['host']

	run_m, run_r = False, False
	for option, value in opts:
		if option == "-v":
			verbose = True
		if option == "--db":
			db = value
		if option == '--port':
			port = int(value)
		if option == '--host':
			host = value
		if option in ("-h", "--help"):
			raise Usage(help_message)
			
	from bourbon.manager import JobManager
	em = JobManager(db)
	print em
	
	print 'Starting RPC Server'
	em.start_server( host=host, port=port )

def run_pbs(args):
	try:
		opts, args = getopt.getopt(args, "mr", ["help","address=","max="])
	except getopt.error, msg:
		raise Usage(msg)

	# option processing
	address = None
	maxjobs = 10
	data = load_defaults()
	if 'manager_address' in data: address = data['manager_address']
	if 'max_jobs' in data: maxjobs = data['max_jobs']
	
	for option, value in opts:
		if option == "--address":
			address = value
		if option in ("-h", "--help"):
			raise Usage(help_message)
		if option == "--max":
			maxjobs = int(value)
			
	from bourbon.pbsrunner import PBSJobRunner
	
	if address is not None:
		er = PBSJobRunner(address, max_jobs = maxjobs)
	else:
		er = PBSJobRunner(max_jobs = maxjobs)
	
	print 'Starting PBSJobRunner...'
	er.start()
	
def run_file(args):
	try:
		opts, args = getopt.getopt(args, "", ["input=","output="])
	except getopt.error, msg:
		raise Usage(msg)

	# option processing
	address = None
	data = load_defaults()
	if 'manager_address' in data: address = data['manager_address']
	for option, value in opts:
		if option == "--input":
			finput = value
		elif option == '--output':
			foutput = value
		if option in ("-h", "--help"):
			raise Usage(help_message)
			
	from bourbon.pbsrunner import FileJobRunner
	
	print 'Starting FileJobRunner...'
	er = FileJobRunner(finput, foutput)
		
	er.start()
	
def run_runner(args):
	arg = args[0]
	if arg == 'pbs': 
		run_pbs(args[1:])
	elif arg == 'file':
		run_file(args[1:])
	elif arg == 'rpc':
		run_rpc(args[1:])

	
def run_rpc(args):
	try:
		opts, args = getopt.getopt(args, "mr", ["help","address=","input=","output="])
	except getopt.error, msg:
		raise Usage(msg)

	# option processing
	address = None
	data = load_defaults()
	if 'manager_address' in data: address = data['manager_address']
	for option, value in opts:
		if option == "--address":
			address = value
		if option in ("-h", "--help"):
			raise Usage(help_message)
			
	from bourbon.runner import RPCJobRunner
	
	if address is not None:
		er = RPCJobRunner(address)
	else:
		er = RPCJobRunner()
		
	print 'Starting RPCJobRunner...'
	er.start()
		
class Usage(Exception):
	def __init__(self, msg):
		self.msg = msg


def main(argv=None):
	if argv is None:
		argv = sys.argv
	try:
		if len(argv) >= 2:
			if argv[1] == 'manager':
				run_manager(argv[2:])
			elif argv[1] == 'runner':
				run_runner(argv[2:])
	
	except Usage, err:
		print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
		print >> sys.stderr, "\t for help use --help"
		return 2


if __name__ == "__main__":
	sys.exit(main())
